package com.guanyong.services;

import com.guanyong.dao.IUserInfoDaoMapper;
import com.guanyong.model.UserBaseModel;
import com.guanyong.dao.IUserBaseDaoMapper;

import com.guanyong.model.UserInfoModel;
import com.guanyong.model.UserLoginLogModel;
import com.guanyong.utils.Cache.ICahce.ICache;
import com.guanyong.utils.Comm.ResultCode;
import com.guanyong.utils.Comm.ResultObject;
import com.guanyong.utils.Encrypt.EncryptExt;
import com.guanyong.utils.UniqueID.DBObjectID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.security.PublicKey;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by mxk on 2017/3/24.
 */
@Service
public class UserBaseService {
    @Autowired
    private IUserBaseDaoMapper userBaseDao;

    @Autowired
    UserLoginLogService userLoginLogService;

    @Autowired
    ICache cache;

    @Autowired
    UserInfoService userInfoService;

    @Autowired
    private IUserInfoDaoMapper iUserInfoDaoMapper;

    @Value("${mortise.usercas.model.cacheKey}")
    String casModelCacheKey;
    /**
     * 查询用户信息
     *
     * @param searchID 查询ID
     * @param type     查询类型 1用户id 2手机号 3邮箱 4QQ 5威信 6新浪微博
     * @return
     */
    public UserBaseModel getUserModel(String searchID, int type) {

        UserBaseModel user = null;
        switch (type) {
            case 1:
                Object model = cache.get(casModelCacheKey, searchID);
                if (model == null) {
                    user = userBaseDao.selectByPrimaryKey(searchID);
                    if (user != null) {
                        cache.put(casModelCacheKey, searchID, user);
                    }
                } else {
                    user = (UserBaseModel) model;
                }
                break;
            case 2:
                user = userBaseDao.selectUserByPhone(searchID);
                break;
            case 3:
                user = userBaseDao.selectUserByEmail(searchID);
                break;
            case 4:
                user = userBaseDao.selectUserByQqOpenId(searchID);
                break;
            case 5:
                user = userBaseDao.selectUserByWechatOpenId(searchID);
                break;
            case 6:
                user = userBaseDao.selectUserByWeiboOpenId(searchID);
                break;
        }
        return user;
    }


    public ResultObject<UserBaseModel> LoginUserByOpenId(Integer type,
                                                         String openid,
                                                         String name,
                                                         String photo,
                                                         String sex,
                                                         String ip,
                                                         Integer loginapp){
        ResultObject<UserBaseModel> resultObject =new ResultObject<UserBaseModel>();
        if (openid == null || openid.equals("")) {
            resultObject.setCode(ResultCode.ParamsError);
            resultObject.setErrorMsg("输入openid不能为空");
        }
        String openidMd5=com.guanyong.utils.Encrypt.EncryptExt.GetMd5Code(openid);
        UserBaseModel userBaseModel=getUserModel(openidMd5,type);
        if (userBaseModel!=null){
            resultObject.setResult(userBaseModel);
            resultObject.setCode(ResultCode.LoginSucess);
            //写如日志
            UserLoginLogModel userLoginLogModel =new UserLoginLogModel();
            userLoginLogModel.setfLoginapp(loginapp);
            userLoginLogModel.setfUserid(userBaseModel.getfId());
            userLoginLogModel.setfLoginip(ip);
            userLoginLogService.AddLoginLog(userLoginLogModel);
        }
        else{
            //注册。。。
            resultObject=  userInfoService.RegUserOpenid(photo,name,openidMd5,type,sex,loginapp);


        }
        return resultObject;
    }




    /**
     * 用户名、手机号、邮箱登录
     *
     * @param loginID  用户名、手机号、邮箱 方法内部通过正则判断
     * @param password
     * @return
     */
    public ResultObject<UserBaseModel> UserLogin(String loginID, String password,Integer
            loginType,String ip,Integer loginapp) {
        ResultObject<UserBaseModel> resultObject = new ResultObject<UserBaseModel>();
        if (loginID == null || loginID.equals("")) {
            resultObject.setCode(ResultCode.ParamsError);
            resultObject.setErrorMsg("登录Id参数错误");
        }
        if (password == null || password.equals("")) {
            resultObject.setCode(ResultCode.ParamsError);
            resultObject.setErrorMsg("输入密码参数错误");
        }
        UserBaseModel userBaseModel=getUserModel(loginID,loginType);
        if (userBaseModel!=null){
            //手机号 密码登录
            if (userBaseModel.getfState() == 0||userBaseModel.getfState() == 2) {
                if (EncryptExt.GetMd5Code(userBaseModel.getfId() + password)
                        .equals(userBaseModel.getfPassword())) {
                    //登录成功
                    resultObject.setResult(userBaseModel);
                    resultObject.setCode(ResultCode.LoginSucess);
                    //写如日志
                    UserLoginLogModel userLoginLogModel =new UserLoginLogModel();
                    userLoginLogModel.setfLoginapp(loginapp);
                    userLoginLogModel.setfUserid(userBaseModel.getfId());
                    userLoginLogModel.setfLoginip(ip);
                    userLoginLogService.AddLoginLog(userLoginLogModel);

                } else {
                    resultObject.setCode(ResultCode.LoginPassError);
                    resultObject.setErrorMsg("密码错误");
                }
            } else {
                resultObject.setCode(ResultCode.UserLocck);
                resultObject.setErrorMsg("用户被锁定");
            }
        }
        else{
            resultObject.setCode(ResultCode.LoginFail);
            resultObject.setErrorMsg("没有找到用户");
        }
        return resultObject;

    }

    public HashMap<String,Object> GetUserBaseList(UserBaseModel userBaseModel,
                                                  Integer pno,
                                                  Integer pagesize,
                                                  Integer allcount){
        HashMap<String,Object> hashMap=new HashMap();
        if (allcount<0){
            Integer count=userBaseDao
                    .SelectUserBaseListCount(userBaseModel);
            hashMap.put("count",count);
        }
        else {
            hashMap.put("count",allcount);
        }
        List<UserBaseModel> userBaseModelList
                =userBaseDao.SelectUserBaseList(userBaseModel,(pno-1)*pagesize,
                pagesize);
        hashMap.put("list",userBaseModelList);
        return hashMap;
    }


    /**
     * 用于根据ID模拟登录
     *
     * @param id
     * @param password
     * @return
     */
    public ResultObject<UserBaseModel> loginByPrimekey(String id, String password) {
        ResultObject<UserBaseModel> resultObject = new ResultObject<UserBaseModel>();
        if (id == null || id.equals("")) {
            resultObject.setCode(ResultCode.ParamsError);
            resultObject.setErrorMsg("登录fId参数错误");
            return resultObject;
        }
        UserBaseModel userBaseModel = getUserModel(id,1);
        if (userBaseModel != null) {
            if (userBaseModel.getfState() == 1) {
                if (password.equals(userBaseModel.getfPassword())) {
                    //登录成功
                    resultObject.setResult(userBaseModel);
                    resultObject.setCode(ResultCode.LoginSucess);
                } else {
                    resultObject.setCode(ResultCode.LoginPassError);
                    resultObject.setErrorMsg("密码错误");
                }
            } else {
                resultObject.setCode(ResultCode.UserLocck);
                resultObject.setErrorMsg("用户被锁定");
            }

        } else {
            resultObject.setCode(ResultCode.LoginFail);
            resultObject.setErrorMsg("没有找到用户");

        }
        return resultObject;

    }
    public boolean isEmail(String email) {
        String regEx = "[a-zA-Z_]{1,}[0-9]{0,}@(([a-zA-z0-9]-*){1,}\\.){1,3}[a-zA-z\\-]{1,}";
        // 编译正则表达式
        Pattern pattern = Pattern.compile(regEx);
        // 忽略大小写的写法
        // Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(email);
        // 字符串是否与正则表达式相匹配
        return matcher.matches();
    }

    public boolean isPhone(String phone) {
        String regEx = "^1[34578]\\d{9}$";
        // 编译正则表达式
        Pattern pattern = Pattern.compile(regEx);
        // 忽略大小写的写法
        // Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(phone);
        // 字符串是否与正则表达式相匹配
        return matcher.matches();

    }

    /**
     * 插入用户
     *
     *
     * @return
     */
    public ResultObject<Integer> insert(String userName,String userPhone,String userPwd,Integer
            role,String photo) {

        ResultObject<Integer> resultObject = new ResultObject<Integer>();
        if (userPwd == null || userPwd.equals("")) {
            resultObject.setCode(ResultCode.ParamsError);
            resultObject.setErrorMsg("用户密码参数错误");
        }

        if (userPhone != null && !userPhone.equals("")) {
            if (isPhone(userPhone)) {
                UserBaseModel _user = getUserModel(userPhone,2);
                if (_user!=null) {
                    resultObject.setCode(ResultCode.FiledRepeat);
                    resultObject.setErrorMsg("手机已存在");
                }
            } else {
                resultObject.setCode(ResultCode.ParamsError);
                resultObject.setErrorMsg("手机号式错误");
            }

        }
        else{
            resultObject.setCode(ResultCode.ParamsError);
            resultObject.setErrorMsg("用户手机号参数错误");
        }
        if (role<1){
            resultObject.setCode(ResultCode.ParamsError);
            resultObject.setErrorMsg("角色参数不正确");
        }

        if (resultObject.getErrorMsg().length() == 0) {
            if (resultObject.getErrorMsg() == null || resultObject.getErrorMsg().equals("")) {
                //调用添加；
                String newuserid = new DBObjectID().toString();
                if (newuserid != null && !newuserid.equals("")) {
                    UserBaseModel newUserModel=new UserBaseModel();
                    newUserModel.setfId(newuserid);
                    String passwordMd5 = EncryptExt.GetMd5Code(newuserid + userPwd);
                    newUserModel.setfPassword(passwordMd5);
                    newUserModel.setfUsername(userName);
                    newUserModel.setfPhone(userPhone);
                    newUserModel.setfRole(role);
                    newUserModel.setfPhoto(photo);
                    //填写默认值
                    newUserModel.setfEmail("");
                    newUserModel.setfState(0);
                    newUserModel.setfRegapp(1);
                    newUserModel.setfQqopenid("");
                    newUserModel.setfWechatopenid("");
                    newUserModel.setfWeibopenid("");
                    int res = userBaseDao.insert(newUserModel);
                    if (res > -1) {
                        resultObject.setCode(ResultCode.OperateOk);
                        resultObject.setResult(1);
                        cache.put(casModelCacheKey, newUserModel.getfId(), newUserModel);
                    } else {
                        resultObject.setCode(ResultCode.OperateFail);
                        resultObject.setErrorMsg("添加用户失败");
                    }
                } else {
                    resultObject.setCode(ResultCode.ServiceError);
                    resultObject.setErrorMsg("生成用户id报错");
                }
            }
        }
        return resultObject;
    }
//
//    /**
//     * 修改用户基本信息(修改密码请调用下边的修改密码方法)
//     *
//     * @param record 用户对象
//     * @return 成功返回ResultCode.OperateOk  失败返回ResultCode.OperateFail
//     */
//    public ResultObject<Integer> update(UserBaseModel record) {
//        ResultObject<Integer> resultObject = new ResultObject<Integer>();
//        //登录名不允许修改，所以注释下边这段代码
////        if (record.getfUsername() != null && !record.getfUsername().equals("")) {
////            if (isUserName(record.getfUsername())) {
////                String logindIdMd5 = EncryptExt.GetMd5Code(record.getfUsername());
////                record.setfUsername_md5(logindIdMd5);
////                ResultObject<UserBaseModel> _user = getUserByUserName(logindIdMd5);
////                if (!_user.getCode().equals(ResultCode.NoResult) && _user.getResult() != null && !_user.getResult().getfId().equals(record.getfId())) {
////                    resultObject.setCode(ResultCode.FiledRepeat);
////                    resultObject.setErrorMsg("登录名已存在");
////                }
////            } else {
////                resultObject.setCode(ResultCode.ParamsError);
////                resultObject.setErrorMsg("用户名格式错误");
////            }
////        }
//        int modifyPhone=0 , modifyEmail=0;
//        if (record.getfEmail() != null && !record.getfEmail().equals("")) {
//            if (isEmail(record.getfEmail())) {
//                ResultObject<UserBaseModel> _user = getUserByEmail(record.getfEmail());
//                if (!_user.getCode().equals(ResultCode.NoResult) && _user.getResult() != null && !_user.getResult().getfId().equals(record.getfId())) {
//                    resultObject.setCode(ResultCode.FiledRepeat);
//                    resultObject.setErrorMsg("邮箱已存在");
//                } else {
//                    modifyEmail=1;
//                }
//            } else {
//                resultObject.setCode(ResultCode.ParamsError);
//                resultObject.setErrorMsg("邮箱格式错误");
//            }
//
//        }
//        if (record.getfPhone() != null && !record.getfPhone().equals("")) {
//            if (isPhone(record.getfPhone())) {
//                ResultObject<UserBaseModel> _user = getUserByPhone(record.getfPhone());
//                if (!_user.getCode().equals(ResultCode.NoResult) && _user.getResult() != null && !_user.getResult().getfId().equals(record.getfId())) {
//                    resultObject.setCode(ResultCode.FiledRepeat);
//                    resultObject.setErrorMsg("手机已存在");
//                }else{
//                    modifyPhone=1;
//                }
//            } else {
//                resultObject.setCode(ResultCode.ParamsError);
//                resultObject.setErrorMsg("手机号式错误");
//            }
//
//        }
//        if (resultObject.getErrorMsg().length() == 0) {
//            int res = userBaseDao.updateByPrimaryKeySelective(record);
//            if (res > 0) {
//
//               // cache.put(casModelCacheKey, record.getfId(), record);
//                resultObject.setCode(ResultCode.OperateOk);
//            } else {
//                resultObject.setCode(ResultCode.OperateFail);
//            }
//        }
//
//        return resultObject;
//    }


    /**
     * 修改用户基本信息
     *
     * @param uid 用户ID
     * @param path 头像路径
     * @return 成功返回ResultCode.OperateOk  失败返回ResultCode.OperateFail
     */
    public ResultObject<Integer> updatePhoto(String uid,String path) {
        ResultObject<Integer> resultObject = new ResultObject<Integer>();
        UserBaseModel userBaseModel=new UserBaseModel();
        userBaseModel.setfId(uid);
        userBaseModel.setfPhoto(path);
        Integer res= userBaseDao.updateByPrimaryKeySelective(userBaseModel);
        if (res >-1){
            resultObject.setCode(ResultCode.OperateOk);
        }
        else{
            resultObject.setCode(ResultCode.OperateFail);
        }
        return resultObject;
    }
    public ResultObject<String> updateUserName1_0(String uid,String username) {
        ResultObject<String> resultObject = new ResultObject<String>();
        UserBaseModel userBaseModel=new UserBaseModel();
        userBaseModel.setfId(uid);
        userBaseModel.setfUsername(username);
        Integer res= userBaseDao.updateByPrimaryKeySelective(userBaseModel);
        if (res >-1){
            resultObject.setCode(ResultCode.OperateOk);
            resultObject.setResult(username);
        }
        else{
            resultObject.setCode(ResultCode.OperateFail);
        }
        return resultObject;
    }

    public ResultObject<String> updatePhoto1_0(String uid,String path) {
        ResultObject<String> resultObject = new ResultObject<String>();
        UserBaseModel userBaseModel=new UserBaseModel();
        userBaseModel.setfId(uid);
        userBaseModel.setfPhoto(path);
        Integer res= userBaseDao.updateByPrimaryKeySelective(userBaseModel);
        if (res >-1){
            resultObject.setCode(ResultCode.OperateOk);
            resultObject.setResult(path);
        }
        else{
            resultObject.setCode(ResultCode.OperateFail);
        }
        return resultObject;
    }


    public ResultObject<Integer> updatePhone(String uid,String Phone) {
        ResultObject<Integer> resultObject = new ResultObject<Integer>();
        UserBaseModel userBaseModel=new UserBaseModel();
        userBaseModel.setfId(uid);
        userBaseModel.setfPhone(Phone);
        Integer res= userBaseDao.updateByPrimaryKeySelective(userBaseModel);
        if (res >-1){
            resultObject.setCode(ResultCode.OperateOk);
        }
        else{
            resultObject.setCode(ResultCode.OperateFail);
        }
        return resultObject;
    }




    public ResultObject<Integer> updateUserName(String uid,String username) {
        ResultObject<Integer> resultObject = new ResultObject<Integer>();
        UserBaseModel userBaseModel=new UserBaseModel();
        userBaseModel.setfId(uid);
        userBaseModel.setfUsername(username);
        Integer res= userBaseDao.updateByPrimaryKeySelective(userBaseModel);
        if (res >-1){
            resultObject.setCode(ResultCode.OperateOk);
        }
        else{
            resultObject.setCode(ResultCode.OperateFail);
        }
        return resultObject;
    }

    public ResultObject<Integer> forgetPwd(String phone,String pwd){
        ResultObject<Integer> resultObject = new ResultObject<Integer>();
        UserBaseModel userBaseModel=getUserModel(phone,2);
        if (userBaseModel!=null ){
            String oldPwdMd5=EncryptExt.GetMd5Code(userBaseModel.getfId() + pwd);
            UserBaseModel userBaseNewModel=new UserBaseModel();
            userBaseNewModel.setfId(userBaseModel.getfId());
            userBaseNewModel.setfPassword(oldPwdMd5);
            Integer res= userBaseDao.updateByPrimaryKeySelective(userBaseNewModel);
            if (res >-1){
                resultObject.setCode(ResultCode.OperateOk);
            }
            else{
                resultObject.setCode(ResultCode.OperateFail);
            }
        }
        else{
            resultObject.setCode(ResultCode.NoResult);
            resultObject.setErrorMsg("没有找到用户");
        }
        return resultObject;
    }

    /**
     * 修改用户密码
     *
     * @param uid 用户ID
     * @param oldPwd 头像路径
     * @param newPwd 新密码
     * @return 成功返回ResultCode.OperateOk  失败返回ResultCode.OperateFail
     */
    public ResultObject<Integer> updatePwd(String uid,String oldPwd,String newPwd) {
        ResultObject<Integer> resultObject = new ResultObject<Integer>();
        UserBaseModel userBaseModel=getUserModel(uid,1);
        if(userBaseModel==null){
            resultObject.setCode(ResultCode.NoResult);
        }else {
            String oldPwdMd5=EncryptExt.GetMd5Code(uid + oldPwd);
            if(!oldPwdMd5.equals(userBaseModel.getfPassword())){
                resultObject.setCode(ResultCode.LoginPassError);
            }else{
                UserBaseModel userBaseNewModel=new UserBaseModel();
                userBaseNewModel.setfId(uid);
                userBaseNewModel.setfPassword(EncryptExt.GetMd5Code(uid + newPwd));
                Integer res= userBaseDao.updateByPrimaryKeySelective(userBaseModel);
                if (res >-1){
                    resultObject.setCode(ResultCode.OperateOk);
                }
                else{
                    resultObject.setCode(ResultCode.OperateFail);
                }
            }

        }

        return resultObject;
    }

    //修改密码
    public ResultObject<Integer> updatePwd(String uid,String newPwd) {
        ResultObject<Integer> resultObject = new ResultObject<Integer>();
        UserBaseModel userBaseModel=getUserModel(uid,1);
        if(userBaseModel==null){
            resultObject.setCode(ResultCode.NoResult);
        }else {
            String PwdMd5=EncryptExt.GetMd5Code(uid + newPwd);
            UserBaseModel userBaseNewModel=new UserBaseModel();
            userBaseNewModel.setfId(uid);
            userBaseNewModel.setfPassword(PwdMd5);
            Integer res= userBaseDao.updateByPrimaryKeySelective(userBaseModel);
            if (res >-1){
                resultObject.setCode(ResultCode.OperateOk);
            }
            else{
                resultObject.setCode(ResultCode.OperateFail);
            }

        }

        return resultObject;
    }

    /**
     * 修改用户状态
     *
     * @param uid 用户ID
     * @param state 用户状态 （1 正常 0锁定）
     * @return 成功返回ResultCode.OperateOk  失败返回ResultCode.OperateFail
     */
    public ResultObject<Integer> updateState(String uid,Integer state) {
        ResultObject<Integer> resultObject = new ResultObject<Integer>();
        UserBaseModel userBaseModel=new UserBaseModel();
        userBaseModel.setfId(uid);
        userBaseModel.setfState(state);
        Integer res= userBaseDao.updateByPrimaryKeySelective(userBaseModel);

        if (res >-1){
            resultObject.setCode(ResultCode.OperateOk);
        }
        else{
            resultObject.setCode(ResultCode.OperateFail);
        }
        return  resultObject;
    }
//
//    /**
//     * 修改用户邮箱
//     *
//     * @param uid 用户ID
//     * @param email 邮箱
//     * @return 成功返回ResultCode.OperateOk  失败返回ResultCode.OperateFail
//     */
//    public ResultObject<Integer> updateEmail(String uid,String email) {
//        UserBaseModel userBaseModel=new UserBaseModel();
//        userBaseModel.setfId(uid);
//        userBaseModel.setfEmail(email);
//        return update(userBaseModel);
//    }
//
//    /**
//     * 修改用户手机号
//     *
//     * @param uid 用户ID
//     * @param phone 手机号
//     * @return 成功返回ResultCode.OperateOk  失败返回ResultCode.OperateFail
//     */
//    public ResultObject<Integer> updatePhone(String uid,String phone) {
//        UserBaseModel userBaseModel=new UserBaseModel();
//        userBaseModel.setfId(uid);
//        userBaseModel.setfPhone(phone);
//        return update(userBaseModel);
//    }


    /**
     * 用户绑定第三方
     *
     * @param
     * @param
     * @return
     */
    public ResultObject<UserBaseModel> bindingOpenid(UserBaseModel userBaseModel,
                                               Integer type,
                                               String openid,
                                               String name,
                                               String photo,
                                               String sex,
                                               String ip,
                                               Integer loginapp) {
        ResultObject<UserBaseModel> resultObject = new ResultObject<UserBaseModel>();

        if (userBaseModel.getfPhone() != null && !userBaseModel.getfPhone().equals("")) {
            userBaseModel.setfUsername(name);
            userBaseModel.setfRole(0);
            userBaseModel.setfPhoto(photo);
            //填写默认值
            userBaseModel.setfEmail("");
            userBaseModel.setfState(0);
            userBaseModel.setfRegapp(loginapp);
            String openidMd5 =null;
            Integer res =-1;
            if(openid==null || "".equals(openid)){
                if (type==4){
                    res =userBaseDao.upNullQqopenid(userBaseModel.getfId());
                }
                else if(type==5){
                    res =userBaseDao.upNullWechatopenid(userBaseModel.getfId());
                }
                else if(type==6){
                    res =userBaseDao.upNullWeibopenid(userBaseModel.getfId());
                }
            }else{
                openidMd5=com.guanyong.utils.Encrypt.EncryptExt.GetMd5Code(openid);
                if (type==4){
                    userBaseModel.setfQqopenid(openidMd5);
                }
                else if(type==5){
                    userBaseModel.setfWechatopenid(openidMd5);
                }
                else if(type==6){
                    userBaseModel.setfWeibopenid(openidMd5);
                }
                res= userBaseDao.updateByPrimaryKeySelective(userBaseModel);
            }

            if (res > -1) {
                UserInfoModel userInfoModel=new UserInfoModel();
                userInfoModel.setfId(userBaseModel.getfId());
                userInfoModel.setfSex(sex);
                userInfoModel.setfLastloginapp(loginapp);
                userInfoModel.setfLastlogintime(new Date( ));
                Integer res2=iUserInfoDaoMapper.update(userInfoModel);
                if (res2>-1)
                {
                    resultObject.setCode(ResultCode.OperateOk);
                    resultObject.setResult(userBaseModel);
                    cache.put(casModelCacheKey, userBaseModel.getfId(), userBaseModel);
                    //写入cookie
                }
                else{
                    resultObject.setCode(ResultCode.OperateFail);
                    resultObject.setErrorMsg("绑定失败");
                }

            } else {
                resultObject.setCode(ResultCode.OperateFail);
                resultObject.setErrorMsg("添加用户失败");
            }
        } else {
            resultObject.setCode(ResultCode.NoLogin);
            resultObject.setErrorMsg("请先登录");
        }

        return  resultObject;
















    }
}
